<template>
  <el-container class="main-layout">
    <el-header>
      <div class="header-content">
        <div class="logo">企业招聘系统</div>
        <el-menu mode="horizontal" :router="true" :default-active="activeMenu">
          <el-menu-item index="/jobs">招聘管理</el-menu-item>
          <el-menu-item index="/forum">论坛交流</el-menu-item>
          <el-menu-item index="/evaluation">学生评价</el-menu-item>
        </el-menu>
        <div class="user-info">
          <el-dropdown @command="handleCommand" v-if="isLoggedIn">
            <span class="el-dropdown-link">
              {{ username }}<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="profile">个人中心</el-dropdown-item>
              <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
    </el-header>
    <el-main>
      <router-view @login-success="checkLoginStatus"></router-view>
    </el-main>
  </el-container>
</template>

<script>
export default {
  name: 'MainLayout',
  data() {
    return {
      activeMenu: '',
      isLoggedIn: false,
      username: ''
    }
  },
  methods: {
    handleCommand(command) {
      if (command === 'logout') {
        localStorage.clear()
        this.isLoggedIn = false
        this.username = ''
        this.$router.replace('/login')
        this.$message.success('已退出登录')
      } else if (command === 'profile') {
        this.$router.push('/enterprise/profile')
      }
    },
    checkLoginStatus() {
      const token = localStorage.getItem('token')
      const username = localStorage.getItem('username')
      this.isLoggedIn = !!token
      this.username = username || ''
    }
  },
  watch: {
    '$route': {
      handler() {
        this.checkLoginStatus()
        this.activeMenu = this.$route.path
      },
      immediate: true
    }
  },
  created() {
    this.checkLoginStatus()
  },
  mounted() {
    window.addEventListener('storage', this.checkLoginStatus)
  },
  beforeDestroy() {
    window.removeEventListener('storage', this.checkLoginStatus)
  }
}
</script>

<style scoped>
.main-layout {
  min-height: 100vh;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
}

.logo {
  font-size: 20px;
  font-weight: bold;
}

.user-info {
  cursor: pointer;
}
</style> 